import { ConfigService } from '@nestjs/config';
import { UserEntity } from './../../entities/user.entity';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { CreateUserDto } from './dto/create.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private userRepository: Repository<UserEntity>,
    private configService: ConfigService,
  ) {}

  async findAll() {
    // const dbUser = this.configService.get('mysql.host');
    let [userList, count] = await this.userRepository.findAndCount();
    return {list: userList, count};
  }

  async findByName(username) {
    return await this.userRepository.findOne({username: username});
  }

  // 根据用户名模糊查找用户
  async getUsersByName(username: string) {
    let findList = await this.userRepository.find({
      where: {username: Like(`%${username}%`)}
    });
    return findList;
  }

  // 创建用户
  async createUser(data: CreateUserDto) {
    const findUser = await this.userRepository.find({username: data.username});
    if (findUser.length > 0) {
      throw new UnauthorizedException('用户名已存在。');
    }
    const newUser = await this.userRepository.create(data);
    await this.userRepository.save(newUser);
    return newUser;
  }
}
